package wechat

import (
	"github.com/gogf/gf/container/gmap"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/text/gstr"
	"github.com/gogf/gf/util/gconv"
	"github.com/silenceper/wechat"
	"github.com/silenceper/wechat/cache"
)

type Wechat struct {
	WxClient *wechat.Wechat
}

var (
	instances   = gmap.NewStrAnyMap(true)
	DefaultName = "default"
)

func Instance(name ...string) *Wechat {
	key := DefaultName
	if len(name) > 0 && name[0] != "" {
		key = "wechat." + name[0]
	} else {
		key = "wechat." + key
	}
	return instances.GetOrSetFuncLock(key, func() interface{} {
		return New(key)
	}).(*Wechat)
}

func New(name string) *Wechat {
	config := g.Cfg().GetMapStrStr(name)
	if config == nil {
		panic("获取微信配置失败")
	}
	redisConfig := g.Cfg().GetString("redis.config.default")
	var wechatCache cache.Cache
	if redisConfig != "" {
		rconfig := gstr.Split(redisConfig, ",")
		redisOpts := &cache.RedisOpts{
			Host:        rconfig[0],
			Password:    rconfig[2],
			Database:    gconv.Int(rconfig[1]),
			//MaxActive:   opt.MaxActive,
			//MaxIdle:     opt.MaxIdle,
			//IdleTimeout: opt.IdleTimeout,
		}
		wechatCache = cache.NewRedis(redisOpts)
	} else {
		wechatCache = cache.NewMemory()
	}

	cfg := &wechat.Config{
		AppID:          config["app_id"],
		AppSecret:      config["app_secret"],
		Token:          config["token"],
		EncodingAESKey: config["aes_key"],
		Cache:          wechatCache,
	}
	wxclient := new(Wechat)
	wxclient.WxClient = wechat.NewWechat(cfg)
	return wxclient
}

// 客户端示例
func Client(name ...string) *Wechat {
	return Instance(name...)
}
